package com.bidevalution;

import com.bidevalution.controller.util.RequestUtil;
import com.qtp.common.filter.SessionFilter;
import com.qtp.common.filter.XssFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 查慧英 springboot配置监听器、过滤器和拦截器
 */
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
	@Value("${authLoginUrl}")
	private String authLoginUrl;

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("forward:/index.do");
		registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
	}

	// 配置拦截的资源以及放行的资源
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new HandlerInterceptor() {
			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
					throws Exception {
				RequestUtil.setRequest(request);
				return true;
			}

		}).addPathPatterns("/**");
	}

	@Bean
	public FilterRegistrationBean<XssFilter> xssFilterRegist() {
		FilterRegistrationBean<XssFilter> frBean = new FilterRegistrationBean<XssFilter>();
		frBean.setFilter(new XssFilter());
		frBean.addUrlPatterns("/*");
		System.out.println("filter");
		return frBean;
	}

	@Bean
	public FilterRegistrationBean<SessionFilter> SessionFilterRegist() {
		FilterRegistrationBean<SessionFilter> frBean = new FilterRegistrationBean<SessionFilter>();
		frBean.setFilter(new SessionFilter());
		Map<String, String> params = new HashMap<>(8);
		// params.put("sessionKey","USER_SESSION" );
		// params.put("redirectUrl", "/toLogin.do");
		// params.put("debug", "1");
		// params.put("authLoginUrl", authLoginUrl);
		params.put("excepUrlRegex",
				"/toLogin.do|/login.do|/sysUser/logout.do|/sysUser/login.do|/sysUser/generalCode.do|/resource.*|/runWorkflow/flowDispatch.do|/bidroom/location.do|/beSectionSign/(getWxConfig|sectionSign).do|/facecheck/callback.do|/live/index.do");
		frBean.setInitParameters(params);
		frBean.addUrlPatterns("");
		return frBean;
	}
}
